/**
 * @COPYRIGHT Shanghai RaxTone-Tech Co.,Ltd.
 * @Title: LoginActivity.java  
 * @Description: TODO 
 * @author jiajing.mo	 
 * @date 2012-9-11
 * @version V1.0 
 * 
 * Modification History: 
 * @date 2012-9-11  |  jiajing.mo  |  Created 
 */
package com.morn.fanfou.authenticator;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.morn.fanfou.FanfouApplication;
import com.morn.fanfou.MainActivity;
import com.morn.fanfou.R;
import com.morn.fanfou.api.Fanfou;
import com.morn.fanfou.model.OAuthToken;
import com.morn.fanfou.util.Constants;

/**
 * Description: TODO.<br>
 * <p>
 * 
 * @author jiajing.mo
 * @version V1.0
 */
public class LoginActivity extends AccountAuthenticatorActivity {

	private EditText mUsernameEdit;

	private EditText mPasswordEdit;

	private Button mLoginButton;

	private AccountManager mAccountManager;

	private ProgressDialog mProgressDialog;

	private LoginTask mLoginTask;

	private String mUsername;

	private String mPassword;

	private Fanfou fanfou;

	private boolean authLogin;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		fanfou = ((FanfouApplication) getApplicationContext()).getFanfou();
		setContentView(R.layout.activity_login);
		mAccountManager = AccountManager.get(this);
		mUsernameEdit = (EditText) findViewById(R.id.login_username_edit);
		mPasswordEdit = (EditText) findViewById(R.id.login_password_edit);
		mLoginButton = (Button) findViewById(R.id.login_button);
		authLogin = getIntent().getBooleanExtra(Authenticator.KEY_AUTH_LOGIN, false);
		TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				mLoginButton.setEnabled(userNameTextFieldIsValid() && passwordTextFieldIsValid());
			}

			private boolean userNameTextFieldIsValid() {
				return !TextUtils.isEmpty(mUsernameEdit.getText());
			}

			private boolean passwordTextFieldIsValid() {
				return !TextUtils.isEmpty(mPasswordEdit.getText());
			}
		};
		mUsernameEdit.addTextChangedListener(fieldValidatorTextWatcher);
		mPasswordEdit.addTextChangedListener(fieldValidatorTextWatcher);
	}

	public void loginClick(View v) {

		mUsername = mUsernameEdit.getText().toString().trim();
		mPassword = mPasswordEdit.getText().toString().trim();

		if (mLoginTask != null && mLoginTask.getStatus() == LoginTask.Status.RUNNING) {
			return;
		} else {
			mLoginTask = new LoginTask();
			mLoginTask.execute();
		}

	}

	private void onLoginSuccess(OAuthToken oAuthToken) {
		Toast.makeText(this, "login success!", Toast.LENGTH_SHORT).show();
		final Account account = new Account(mUsername, getString(R.string.account_type));
		Bundle userdata = new Bundle();
		userdata.putString(Constants.KEY_TOKEN_SECRET, oAuthToken.getTokenSecret());
		if (mAccountManager.addAccountExplicitly(account, mPassword, userdata)) {
			mAccountManager.setAuthToken(account, Constants.TOKEN_TYPE, oAuthToken.getToken());
			final Intent result = new Intent();
			result.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
			result.putExtra(AccountManager.KEY_ACCOUNT_TYPE, getString(R.string.account_type));
			result.putExtra(AccountManager.KEY_AUTHTOKEN, oAuthToken.getToken());
			setAccountAuthenticatorResult(result.getExtras());
			setResult(RESULT_OK, result);
			finish();
			if (!authLogin) {
				startActivity(new Intent(this, MainActivity.class));
			}
		}
	}

	private void onLoginFailed() {
		Toast.makeText(this, "login failed!", Toast.LENGTH_SHORT).show();
	}

	private void showProgress() {
		mProgressDialog = ProgressDialog.show(this, null, "login...", true, true);
	}

	private void hideProgress() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
			mProgressDialog = null;
		}
	}

	class LoginTask extends AsyncTask<Object, Object, OAuthToken> {

		@Override
		protected void onPreExecute() {
			showProgress();
		}

		@Override
		protected OAuthToken doInBackground(Object... params) {
			try {
				return fanfou.getOAuthToken(mUsername, mPassword);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(OAuthToken result) {
			hideProgress();
			if (result != null) {
				onLoginSuccess(result);
			} else {
				onLoginFailed();
			}
		}
	}
}
